package com.bingyuan.aipassproject

import android.os.CountDownTimer
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bingyuan.aipassproject.entity.*
import com.bingyuan.aipassproject.socket.event.*
import com.bingyuan.aipassproject.utils.BitmapUtils
import com.bingyuan.aipassproject.utils.ShareUtil
import com.bingyuan.aipassproject.utils.loadCircularImage
import com.bingyuan.aipassproject.view.BaseActivity
import com.bingyuan.aipassproject.view.adapter.MultipleItemAdapter
import com.bingyuan.aipassproject.view.widget.*
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.google.gson.Gson
import kotlinx.android.synthetic.main.activity_home.*
import kotlinx.android.synthetic.main.activity_home.ivRule
import kotlinx.android.synthetic.main.activity_luck_draw.*
import kotlinx.android.synthetic.main.activity_luck_draw.ivBlur
import kotlinx.android.synthetic.main.activity_welcome.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.jetbrains.anko.toast
import retrofit2.http.GET
import java.util.*
import kotlin.collections.ArrayList

class HitGoldActivity : BaseActivity() {

    private lateinit var rulePop: RulePopwindow
    private lateinit var roomBean: LoginRoomResponse
    private lateinit var mGson: Gson
    private lateinit var sendGoldPop: SendGoldPopWindow
    private lateinit var exchangePop: ExchangeCoinPopwindow
    private lateinit var gameRecordPop: GameRecordPopWindow
    private var scoreType = ""
    private var mWaitId = 0

    //当前可砸蛋数
    private var mWaitNum = 0

    private lateinit var infoList: ArrayList<EventMsgResponse>
    private lateinit var recordAdapter: MultipleItemAdapter

    private lateinit var sendDetailPop: SendDetailPop

    //丢蛋列表
    private lateinit var sendList: ArrayList<SendRecordResponse.ListBean.DataBean>

    //砸蛋列表
    private lateinit var robList: ArrayList<RobRecordResponse.ListBean.DataBean>

    override fun getLayoutResId(): Int {
        return R.layout.activity_luck_draw
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().post(LogOutEvent(true))
        EventBus.getDefault().unregister(this)
    }

    //其他用户丢蛋或砸蛋消息
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onGetMessage(event: EventMsgEvent) {
        val bean = mGson.fromJson(event.json, EventMsgResponse::class.java)
        infoList.add(0, bean)
        recordAdapter.setNewInstance(infoList)
        recordAdapter.notifyDataSetChanged()
    }

    //房间内记录
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onGetMessage(event: RoomRecordEvent) {
        sendList = event.sendList
        robList = event.robList
        if (robList.size != 0 && sendList.size != 0) {
            ivBlur.visibility = View.VISIBLE
            gameRecordPop = object : GameRecordPopWindow(this, event.sendList, event.robList) {
                override fun onDisMiss() {
                    ivBlur.visibility = View.GONE
                }
            }
            gameRecordPop.show()
        }
    }

    //丢蛋详情弹窗
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onGetMessage(event: SendDetailEvent) {
        ivBlur.visibility = View.VISIBLE
        sendDetailPop = object : SendDetailPop(this, event.json) {
            override fun onDisMiss() {
                ivBlur.visibility = View.GONE
            }
        }
        sendDetailPop.show()
    }

    //丢蛋成功
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onGetMessage(event: SendEggSuccessEvent) {
        //刷新页面
        val getUserResponse = mGson.fromJson(event.json, GetUserResponse::class.java)
        if (getUserResponse.wait_num != 0) {
            tvWaitNum.visibility = View.VISIBLE
            tvWaitNum.text = "" + getUserResponse.wait_num
            ivGoldEggs.visibility = View.VISIBLE
            ivHammer.visibility = View.VISIBLE
        } else {
            tvWaitNum.visibility = View.INVISIBLE
            ivGoldEggs.visibility = View.INVISIBLE
            ivHammer.visibility = View.INVISIBLE
        }

        if (scoreType == "gold") {
            llHitGoldNum.visibility = View.VISIBLE
            tvHitGoldNum.text = getUserResponse.user_score

            llLockGoldNum.visibility = View.VISIBLE
            tvLockGoldNum.text = getUserResponse.lock_score

            //初始化弹窗
            sendGoldPop = object : SendGoldPopWindow(
                this@HitGoldActivity,
                getUserResponse.user_score,
                getUserResponse.lock_score,
                roomBean.stake_score
            ) {
                override fun onDisMiss() {
                    ivBlur.visibility = View.GONE
                }

                override fun sureSelect(list: ArrayList<String>?, type: Int) {
                    val array = list!!.toArray(arrayOfNulls<String>(list.size)) as Array<String>
                    EventBus.getDefault()
                        .post(SendGoldEvent("RedBags.Send", array, roomBean.rules[type].id))
                }


            }
        } else if (scoreType == "peas") {
            llPeasNum.visibility = View.VISIBLE
            tvPeasNum.text = getUserResponse.drill_score

            //初始化弹窗
            sendGoldPop = object : SendGoldPopWindow(
                this@HitGoldActivity,
                getUserResponse.drill_score,
                roomBean.stake_score
            ) {
                override fun onDisMiss() {
                    ivBlur.visibility = View.GONE
                }

                override fun sureSelect(list: ArrayList<String>?, type: Int) {
                    val array = list!!.toArray(arrayOfNulls<String>(list.size)) as Array<String>
                    EventBus.getDefault()
                        .post(SendGoldEvent("RedBags.Send", array, roomBean.rules[type].id))
                }
            }
        }
    }

    //首页传回个人信息
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onGetMessage(event: UserInfoEvent) {
        val userInfoEntity = mGson.fromJson(event.json, UserInfoResponse::class.java)
        //初始化兑换弹窗
        exchangePop = object : ExchangeCoinPopwindow(
            this,
            userInfoEntity.user_score,
            userInfoEntity.lock_score,
            userInfoEntity.ad_balance
        ) {
            override fun exchange(num: Int) {
                EventBus.getDefault().post(ExchangeCoinEvent("exchange_score", num.toFloat(), true))
            }

            override fun onDisMiss() {
                ivBlur.visibility = View.GONE
            }
        }
    }

    //首页传回砸蛋结束信息，更新waitid
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onGetMessage(event: SendEndMsgEvent) {
        val sendEndMsgResponse = mGson.fromJson(event.json, SendEndMsgResponse::class.java)
        if (sendEndMsgResponse.current_wait != null) {
            if (sendEndMsgResponse.current_wait.id != 0) {
                var userId = ShareUtil.getInstance().getString(ShareUtil.USERID, "")
                if (sendEndMsgResponse.current_wait.user_id != userId.toInt()) {
                    mWaitId = sendEndMsgResponse.current_wait.id
                }
            }
        }
    }

    //砸蛋成功
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onGetMessage(event: RobEggsSuccessEvent) {
        val robEggsResponse = mGson.fromJson(event.json, RobEggsResponse::class.java)
        val time = object : CountDownTimer(2000, 1000) {
            override fun onTick(millisUntilFinished: Long) {
                ivGoldEggs.visibility = View.INVISIBLE
                ivHitGoldSuccess.visibility = View.VISIBLE
                tvGetCoinNum.visibility = View.VISIBLE
                tvGetCoinNum.text = robEggsResponse.rob_score
            }

            override fun onFinish() {
                ivHitGoldSuccess.visibility = View.INVISIBLE
                tvGetCoinNum.visibility = View.INVISIBLE
            }
        }.start()

        //砸蛋成功刷新页面
        mWaitNum = robEggsResponse.wait_num
        if (scoreType == "gold") {
            llHitGoldNum.visibility = View.VISIBLE
            tvHitGoldNum.text = robEggsResponse.user_score

            llLockGoldNum.visibility = View.VISIBLE
            tvLockGoldNum.text = robEggsResponse.lock_score
        } else {
            llPeasNum.visibility = View.VISIBLE
            tvPeasNum.text = robEggsResponse.drill_score
        }

        if (mWaitNum != 0) {
            tvWaitNum.visibility = View.VISIBLE
            tvWaitNum.text = "" + robEggsResponse.wait_num
            ivGoldEggs.visibility = View.VISIBLE
            ivHammer.visibility = View.VISIBLE
        } else {
            tvWaitNum.visibility = View.INVISIBLE
            ivGoldEggs.visibility = View.INVISIBLE
            ivHammer.visibility = View.INVISIBLE
        }
    }

    override fun initView() {
        super.initView()
        Glide.with(this).asGif().load(R.drawable.gif_egg).into(ivGoldEggs)
        Glide.with(this).asGif().load(R.drawable.gif_hit_eggs_success).into(ivHitGoldSuccess)
        infoList = ArrayList()
        recordAdapter = MultipleItemAdapter(this, infoList)
        recyclerView.adapter = recordAdapter
        recordAdapter.setOnItemClickListener { adapter, view, position ->
            if (infoList[position].action.equals("Send")) {
                EventBus.getDefault()
                    .post(SendDetailEntity("get_send_detail", infoList[position].order_id))
            }
        }

        recyclerView.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false)
        EventBus.getDefault().register(this)
        mGson = Gson()
        val title = intent.getStringExtra("title")
        tvTitle.text = title
        val json = intent.getStringExtra("json")
        //解析实体类
        roomBean = mGson.fromJson(json, LoginRoomResponse::class.java)
        scoreType = roomBean.score_type
        mWaitNum = roomBean.wait_num
        if (roomBean.current_wait != null) {
            mWaitId = roomBean.current_wait.id
        }
        EventBus.getDefault().post(GetGameRecordEvent(true))
        EventBus.getDefault().post(RoomGetUserInfoEvent(true))

        //初始化兑换弹窗
        exchangePop =
            object : ExchangeCoinPopwindow(this, roomBean.user_score, roomBean.lock_score, "") {
                override fun exchange(num: Int) {
                    exchangePop.dissMiss()
                    EventBus.getDefault()
                        .post(ExchangeCoinEvent("exchange_score", num.toFloat(), true))
                }

                override fun onDisMiss() {
                    ivBlur.visibility = View.GONE
                }
            }

        //开始加载页面布局
        //首选判断是不是练习场
        if (scoreType.equals("gold")) {
            llHitGoldNum.visibility = View.VISIBLE
            tvHitGoldNum.text = roomBean.user_score

            llLockGoldNum.visibility = View.VISIBLE
            tvLockGoldNum.text = roomBean.lock_score

            //初始化弹窗
            sendGoldPop = object : SendGoldPopWindow(
                this@HitGoldActivity,
                roomBean.user_score,
                roomBean.lock_score,
                roomBean.stake_score
            ) {
                override fun onDisMiss() {
                    ivBlur.visibility = View.GONE
                }

                override fun sureSelect(list: ArrayList<String>?, type: Int) {
                    val array = list!!.toArray(arrayOfNulls<String>(list.size)) as Array<String>
                    EventBus.getDefault()
                        .post(SendGoldEvent("RedBags.Send", array, roomBean.rules[type].id))
                }
            }
        } else if (scoreType.equals("peas")) {
            llPeasNum.visibility = View.VISIBLE
            tvPeasNum.text = roomBean.drill_score
            //初始化弹窗
            sendGoldPop = object : SendGoldPopWindow(
                this@HitGoldActivity,
                roomBean.drill_score,
                roomBean.stake_score
            ) {
                override fun onDisMiss() {
                    ivBlur.visibility = View.GONE
                }

                override fun sureSelect(list: ArrayList<String>?, type: Int) {
                    val array = list!!.toArray(arrayOfNulls<String>(list.size)) as Array<String>
                    EventBus.getDefault()
                        .post(SendGoldEvent("RedBags.Send", array, roomBean.rules[type].id))
                }
            }
        }

        //设置头像
        if (!roomBean.face.isNullOrEmpty()) {
            ivHitIcon.loadCircularImage(roomBean.face, 0, this)
//            Glide.with(this).load(roomBean.face).into(ivHitIcon)
        } else {
            Glide.with(this).load(R.drawable.icon_csc).into(ivHitIcon)
        }

        tvUserName.text = roomBean.username
        if (mWaitNum != 0) {
            tvWaitNum.visibility = View.VISIBLE
            tvWaitNum.text = "" + roomBean.wait_num

            ivGoldEggs.visibility = View.VISIBLE
            ivHammer.visibility = View.VISIBLE
        }

        val bitmap = BitmapUtils.getViewBitmap(this, R.layout.activity_luck_draw)
        Glide.with(this).load(bitmap)
            .apply(RequestOptions.bitmapTransform(BlurTransformation(this, 10, 3)))
            .into(ivBlur)
    }

    override fun onClick() {
        ivBack.setOnClickListener {
            finish()
        }

        ivRule.setOnClickListener {
            ivRule.setOnClickListener {
                ivBlur.visibility = View.VISIBLE
                rulePop = object : RulePopwindow(this) {
                    override fun onDisMiss() {
                        ivBlur.visibility = View.GONE
                    }
                }
                rulePop.show()
            }
        }

        ivGoldEggs.setOnClickListener {
            EventBus.getDefault().post(HitGoldEvent("RedBags.Rob", mWaitId))
        }

        ivSmashEggs.setOnClickListener {
            EventBus.getDefault().post(HitGoldEvent("RedBags.Rob", mWaitId))
        }

        ivSendEggs.setOnClickListener {
            ivBlur.visibility = View.VISIBLE
            sendGoldPop.show()
        }

        tvExchangeLock.setOnClickListener {
            ivBlur.visibility = View.VISIBLE
            exchangePop.show()
        }

        ivRecord.setOnClickListener {
            EventBus.getDefault().post(GetRecordEvent(true))
        }
    }

}